package edu.ccut.saturn.manager.bundles.core;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;

public class QueryBundlesbyCondition extends DefaultComponent {
	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		
		String name = (String) parameterContext.getParameterValue(0);
		String key = (String) parameterContext.getParameterValue(1);
		List<SaturnData> allBundleList = (List<SaturnData>) parameterContext
				.getParameterValue(2);

		Pattern keyPattern = null;
		Pattern namePattern = null;
		
		name = name == null?"":name;
		key = key == null?"":key; 
		
		name = "[\u4e00-\u9fa5|a-z|0-9|A-Z]*" + name
				+ "[\u4e00-\u9fa5|a-z|0-9|A-Z]*";

		key = "[\u4e00-\u9fa5|a-z|0-9|A-Z]*" + key
				+ "[\u4e00-\u9fa5|a-z|0-9|A-Z]*";

		keyPattern = Pattern.compile(key);
		namePattern = Pattern.compile(name);
		
		List<SaturnData> appBundleList = new ArrayList<SaturnData>();
		List<SaturnData> delAppBundleList = new ArrayList<SaturnData>();
		
		for (SaturnData bundleInfo : allBundleList) {
			String bundleFilePath = bundleInfo.getString("bundleFilePath");
			if (bundleFilePath != null
					&& bundleFilePath.indexOf("\\plugins") != -1) {

				appBundleList.add(bundleInfo);
			}
		}
		
		for (SaturnData bundleInfo : appBundleList) {
			if (!keyPattern.matcher(bundleInfo.getString("symbolicName")).find()
					|| !namePattern.matcher(bundleInfo.getString("key"))
							.find()) {

				delAppBundleList.add(bundleInfo);
			}
		}
		allBundleList.removeAll(delAppBundleList);
		parameterContext.setParameter(3, allBundleList);
	}
}